using System;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;

namespace ADiKt {
    /// <summary>
    /// displays a loading screen while the content for a screen is loading
    /// </summary>

    class LoadingScreen : Screen {
        bool loadingIsSlow;
        bool otherScreensAreGone;
        Screen[] screensToLoad;

        private LoadingScreen(ScreenManager screenManager, bool loadingIsSlow, Screen[] screensToLoad) {
            this.loadingIsSlow = loadingIsSlow;
            this.screensToLoad = screensToLoad;
            TransitionOnTime = TimeSpan.FromSeconds(0.25f);
        }

        /// <summary> exits all current screens and loads the chosen screens </summary>
        public static void Load(ScreenManager screenManager, bool loadingIsSlow, PlayerIndex? controllingPlayer, params Screen[] screensToLoad) {
            foreach (Screen screen in screenManager.GetScreens())
                screen.ExitScreen();

            LoadingScreen loadingScreen = new LoadingScreen(screenManager, loadingIsSlow, screensToLoad);
            screenManager.AddScreen(loadingScreen, controllingPlayer);
        }

        /// <summary> once the old screens are gone add each new screen in turn </summary>
        public override void Update(GameTime gameTime, bool otherScreenHasFocus, bool coveredByOtherScreen) {
            base.Update(gameTime, otherScreenHasFocus, coveredByOtherScreen);

            if (otherScreensAreGone) {
                ScreenManager.RemoveScreen(this);

                foreach (Screen screen in screensToLoad) {
                    if (screen != null) {
                        ScreenManager.AddScreen(screen, ControllingPlayer);
                    }
                }

                ScreenManager.Game.ResetElapsedTime();
            }
        }


        public override void Draw(GameTime gameTime) {
            if ((ScreenState == ScreenState.Active) && (ScreenManager.GetScreens().Length == 1)) {
                otherScreensAreGone = true;
            }

            //only bothers with message is load is long
            if (loadingIsSlow) {
                SpriteBatch spriteBatch = ScreenManager.SpriteBatch;
                SpriteFont font = ScreenManager.Font;
                const string message = "Loading...";

                // Center the text in the viewport.
                Viewport viewport = ScreenManager.GraphicsDevice.Viewport;
                Vector2 viewportSize = new Vector2(viewport.Width, viewport.Height);
                Vector2 textSize = font.MeasureString(message);
                Vector2 textPosition = (viewportSize - textSize) / 2;
                Color color = Color.White * TransitionAlpha;

                spriteBatch.Begin();
                spriteBatch.DrawString(font, message, textPosition, color);
                spriteBatch.End();
            }
        }
    }
}